<template>
  <div>
    <a-card class="card" title="商品信息" :bordered="false">
      <spu-info-form :fuspudata="spudata" ref="spuInfo" :showSubmit="false" />
    </a-card>
    <a-card class="card" title="规格信息" :bordered="false">
      <sku-info-form
        class="sku"
        ref="skusInfo"
        :showSubmit="false"
        v-for="(item, index) in skuInfos"
        :key="index"
        @deleteIndex="deleteEducation"
        :index="index"
        :item="item"
      />
      <a-button size="large" plain @click="addFormFiled()" type="danger" style="float : left">添加</a-button>
    </a-card>

    <!-- table -->
    <!-- fixed footer toolbar -->
    <footer-tool-bar>
       <a-button type="danger" @click="close" :loading="loading" style="margin-right:30px">关闭</a-button>
      <a-button type="primary" @click="validate" :loading="loading">提交</a-button>
    </footer-tool-bar>
  </div>
</template>

<script>
import FooterToolBar from '@/components/tools/FooterToolBar'
import moment from 'moment'
import pick from 'lodash.pick'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { httpAction, getAction } from '@/api/manage'
import SpuInfoFom from './SpuInfoFom'
import SkuInfoForm from './SkuInfoForm'
import { log } from 'util'
import { filterObj } from '@/utils/util'
export default {
  name: 'ProductSpuModal',
  mixins: [JEditableTableMixin],
  components: {
    FooterToolBar,
    'spu-info-form': SpuInfoFom,
    'sku-info-form': SkuInfoForm
  },
  data() {
    return {
      loading: false,
      // 新增时子表默认添加几行空数据
      goodTypeList: [],
      skuInfos: [],
      categoryName: '',
      shopList: [],
      imageDownloadUri: '/mall-serve/v1/sys/common/getImageByUri?imageUri=',
      spudata: {},
      addDefaultRowNum: 1,
      validatorRules: {
        shopId: {
          rules: [{ required: true, message: '请选择商户' }]
        },
        name: { rules: [{ required: true, message: '请输入SPU 名字!' }] },
        sellPoint: { rules: [{ required: true, message: '请输入卖点!' }] },
        description: { rules: [{ required: true, message: '请输入描述 （商品介绍）!' }] },
        picUrls: { rules: [{ required: true, message: '请添加上商品图片' }] },
        deleted: { rules: [{ required: true, message: '请输入是否删除  ' }] },
        visible: { rules: [{ required: true, message: '请输入是否上架商品' }] }
      },
      refKeys: ['itemMain'],
      activeKey: 'itemMain',

      url: {
        add: '/goodsMain/web/add',
        edit: '/goodsMain/web/edit',
        itemMain: {
          list: '/goodsMain/web/queryItemMainByMainId'
        }
      }
    }
  },
  created() {},
  mounted() {
    this.goodTypeList = []
    this.getGoodsShopListByShopId()
    this.test('product mounted')
  },
  activated() {
    this.addofedit()

    this.test('product activited')
  },
  methods: {
    test(value) {
      console.log(value)
    },
    addofedit() {
      this.$refs.spuInfo.picList = []
      if (this.$route.query.record != undefined) {
        this.spudata = this.$route.query.record
        this.model = Object.assign({}, this.$route.query.record)
        this.model.price=this.model.price/100
        this.model.presentPrice=this.model.presentPrice/100
        this.model.categoryId = parseInt(this.model.categoryId)
        this.$nextTick(() => {
          this.$refs.spuInfo.form.setFieldsValue(
            pick(
              this.model,
              'id',
              'name',
              'shopName',
              'shopId',
              'sellerId',
              'categoryId',
              'categoryName',
              'description',
              'picUrls',
              'price',
              'presentPrice'
            )
          )
          let picurlarr = this.model.picUrls.split(',')
          for (let i in picurlarr) {
            this.$refs.spuInfo.uploadPicList = picurlarr
            this.$refs.spuInfo.picList.push({
              uid: Math.random(),
              name: picurlarr[i],
              url: this.imageDownloadUri + picurlarr[i],
              status: 'done',
              type: 'image/*'
            })
          }
        })
        this.$nextTick(() => {
          let params = { id: this.model.id }
          getAction('/goodsMain/web/queryItemMainByMainId', params).then(res => {
            if (res.success) {
              for(let i in res.result){
                res.result[i].price=res.result[i].price/100
              }
              this.skuInfos = res.result
            }
          })
          // 时间格式化
        })
      } else {
        this.model = {}
        this.spudata = {}
        this.skuInfos = []
        this.$refs.spuInfo.form.resetFields()
      }
    },
    deleteEducation(index) {
      if (index !== 0) {
        this.skuInfos.splice(index, 1)
      }
    },
    addFormFiled() {
      this.skuInfos.push({price:0,quantity:999})
    },
    getGoodsShopListByShopId() {
      getAction('/shopType/getGoodsTypeList')
        .then(res => {
          if (res.success) {
            this.goodTypeList = res.result
          }
        })
        .catch(err => {})
    },
    getGoodTypeChange(value) {
      this.selectedGoodType = value
    },
    //获取商铺可添加的商铺id
    getShopListChange(value) {},
    getShopSearch(value) {
      // if (value.length > 3) {
      let params = { shopName: value }
      getAction('/shop/web/getShopNameList', params).then(res => {
        if (res.success) {
          this.shopList = res.result
        }
        if (res.code === 500) {
          this.$message.warning(res.message)
        }
      })
      // }
    },
    // 最终全页面提交
    validate() {
      const that = this
      this.data = {
        ...this.$refs.spuInfo.form.getFieldsValue(),
        productSkuList: this.skuInfos
      }
      this.data.picUrls = this.$refs.spuInfo.uploadPicList.join()
      this.data.price=this.$refs.spuInfo.form.getFieldValue('price')*100
      this.data.presentPrice=this.$refs.spuInfo.form.getFieldValue('presentPrice')*100
      for(let i in this.data.productSkuList){
        this.data.productSkuList[i].price=this.data.productSkuList[i].price*100
      }
      //触发表单验证
      this.$refs.spuInfo.form.validateFields(
        ['name', 'categoryName', 'shopId', 'description', 'categoryId', 'price', 'presentPrice', 'picUrls'],
        error => {
          if (!error) {
            let httpurl = ''
            let method = ''
            if (!this.$refs.spuInfo.form.getFieldValue('id')) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
           if(this.$refs.spuInfo.form.getFieldValue('price') >= this.$refs.spuInfo.form.getFieldValue('presentPrice')){
              httpAction(httpurl, this.data, method)
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  this.$router.back()
                //  this.$router.push({ path: '/product/ProductSpuList' })
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
                that.close()
              })
           }else{
             that.$message.warning("现价应该小于等于原价");
           }
           
          } else {
            console.log('表单验证' + '错')
          }
        }
      )
    },
    close(){
       this.$router.push({ path: '/product/ProductSpuList' })
    }
  }
}
</script>

<style scoped>
.sku {
  border-top: 1px solid #dee1e6;
}
</style>
